﻿using UnityEngine;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace Net
{
    public partial class AsycUdpClient
    {
        /// <summary>
        /// 接收数据线程
        /// </summary>
        void ReceiveThread()
        {
            while (Connected)
            {
                try
                {
                    IPEndPoint ip = udpAdress;
                    byte[] data = udpSocket.Receive(ref ip);

                    ReceiveData(data);
                }
                catch (Exception e)
                {
                    CatchException(e);
                }
            }
        }
        
        
        
        /// <summary>
        /// 收到数据
        /// </summary>
        /// <param name="data"></param>
        void ReceiveData(byte[] data)
        {
            if (DebugInfo.Data) Debug("Received " + data.Length);

            if (data.Length == 1 && data[0] == pingByte)
            {
                if (Pinging)
                {
                    if (OnPing != null)
                    {
                        OnPing(pingWatch.Elapsed.Milliseconds);
                    }

                    pingWatch = null;
                }
                else
                {
                    udpSocket.Send(data, data.Length);
                }

                return;
            }

            inMessages.Add(new MessageBuffer(data));
            downByteBuffer += data.Length;
            downByteTotal += data.Length;
        }
    }
}

